package com.ciis.base.attach;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * User: zhangdajun
 * Date: 14-4-7
 * Time: 下午4:21
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/fileupload")
public class FileManageCotroller {

    @RequestMapping(value = "/singleImgFile")
    @ResponseBody
    public Model singleImgFile(HttpServletRequest request,@RequestParam("file") MultipartFile file,@RequestParam("dir")String dir, Model model)throws Exception{

        String path = request.getLocalAddr();
        //判断是否有文件
        if (!file.isEmpty()) {
            try {
                String fileName = file.getOriginalFilename();
                // 获取文件后缀
                String extPath = "/"+dir+"/";
                // 判断上传的文件格式是否正确
                String uploadPath = dir;
                uploadPath = this.getClass().getClassLoader().getResource(File.separator).getPath() + ".." + File.separator + ".." + extPath;
                File saveDirFile = new File(uploadPath);
                if (!saveDirFile.exists()) {
                    saveDirFile.mkdirs();
                }
                String uuid = UUID.randomUUID().toString().replaceAll("\\-", "");
                String suffix = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf("."), fileName.length()) : null;
                uploadPath += File.separator+uuid+suffix;
                File filePath = new File(uploadPath);
                if((".png.jpg.gif".indexOf(suffix.toLowerCase())!=-1) || "file".equals(dir)){
                    byte[] bytes = file.getBytes();
                    Integer fileSize = (int)file.getSize()/1024;
                    // 如果文件小于10M，则上传文件，否则提示用户不能超过10M
                    if(fileSize<=10240){
                        //filePath.setWritable(true);
                        // 文件开始上传到服务器上
                        FileCopyUtils.copy(bytes, filePath);
                        model.addAttribute("error",0);
                        if(!"file".equals(dir))
                            model.addAttribute("url","../../"+extPath+uuid+suffix);
                        else
                            model.addAttribute("url","../../"+extPath+uuid+suffix);
                    }else{
                        model.addAttribute("error",1);
                        model.addAttribute("url","上传的文件太大，文件大小不能超过10M");
                    }
                }else{
                    model.addAttribute("error",1);
                    model.addAttribute("url","上传的文件格式不支持");
                }
            } catch (IOException e) {
                e.printStackTrace();
                model.addAttribute("error",1);
                model.addAttribute("url",e.getMessage());

            }
        }
        return model;
    }

    @RequestMapping(value="/uploadFile",method = RequestMethod.POST)
    public @ResponseBody
    HashMap<String,String> uploadFile(HttpServletRequest request, HttpServletResponse response,ModelAndView modelAndView) throws Exception{
        HashMap<String,String> responseObj= new HashMap<String,String>();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        String ymd = sdf.format(new Date());
        String extPath = File.separator+"attach"+File.separator;
        extPath += ymd + File.separator;
        String ctxPath = this.getClass().getClassLoader().getResource(File.separator).getPath() + ".." + File.separator + ".." + extPath;

        //创建文件夹
        File file = new File(ctxPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        String fileName = null;
        String newFileName = null;
        String path=null;
        String suffix = null;
        int size = 0;
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 上传文件名
            MultipartFile mf = entity.getValue();
            fileName = mf.getOriginalFilename();
            String strEnc = String.valueOf(System.currentTimeMillis());
            // 返回一个随机UUID。
            String uuid = UUID.randomUUID().toString().replaceAll("\\-", "");
            suffix = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf("."), fileName.length()) : null;
            newFileName = strEnc + "-" + uuid + (suffix!=null?suffix:"");// 构成新文件名。
            File uploadFile = new File(ctxPath + newFileName);
            try {
                byte[] fbyte = mf.getBytes();
                size = fbyte.length;
                FileCopyUtils.copy(mf.getBytes(), uploadFile);
                path =ctxPath+newFileName;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        responseObj.put("path",path);
        responseObj.put("webPath",extPath+newFileName);
        responseObj.put("name",fileName);
        responseObj.put("size",String.valueOf(size));
        responseObj.put("type",suffix);
        return responseObj;
    }
}
